package com.itheima;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
public class Servlet2 extends HttpServlet {
    private HashMap hm = new HashMap<String,String>();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String realPath = getServletContext().getRealPath("/user.txt");
        System.out.println(realPath);
        BufferedReader br = new BufferedReader(new FileReader(realPath));
        /*ClassLoader classLoader = serlet.class.getClassLoader();
        ClassLoader classLoader1 = new serlet().getClass().getClassLoader();
        ClassLoader classLoader2 = Class.forName("").getClassLoader();
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        String path = systemClassLoader.getResource().getPath();*/
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        ClassLoader parent = systemClassLoader.getParent();
        ClassLoader parent1 = parent.getParent();
        String s;
            while ((s=br.readLine())!=null){
                String[] split = s.split(":");
              if (split.length == 2)  hm.put(split[0],split[1]);
            }
        String id = req.getParameter("id");
        String psw = req.getParameter("psw");
        if (hm.containsKey(id)){
            PrintWriter writer = resp.getWriter();
            writer.print("注册失败");
            //        writer.close(); 这个流不用关,tomcat自动关
        }else{
            BufferedWriter bw = new BufferedWriter(new FileWriter(realPath,true));
            bw.write(id+":"+psw);
            bw.newLine();
            resp.getWriter().write("注册成功");
            bw.close();
        }
    }
}
